package com.liwbn.rbac.service.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.liwbn.rbac.core.orm.mybatis.Page;
import com.liwbn.rbac.dao.UserMapper;
import com.liwbn.rbac.model.User;
import com.liwbn.rbac.model.UserExample;
import com.liwbn.rbac.service.UserService;
import com.liwbn.rbac.vo.UserVO;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public Long insert(User model) {
        userMapper.insert(model);
        return model.getId();
    }

    @Override
    public int insertSelective(User model) {
        return userMapper.insertSelective(model);
    }

    @Override
    public int updateByPrimaryKey(User model) {
        return userMapper.updateByPrimaryKey(model);
    }

    @Override
    public int updateByPrimaryKeySelective(User model) {
        return userMapper.updateByPrimaryKeySelective(model);
    }

    @Override
    public int deleteByPrimaryKey(Long id) {
        return userMapper.deleteByPrimaryKey(id);
    }

    @Override
    public User selectByPrimaryKey(Long id) {
        return userMapper.selectByPrimaryKey(id);
    }

    /**
     * 分页数据查询
     * 
     * @param page
     * @param example
     * @return
     */
    public Page<User> selectPage(Page<User> page, UserExample example) {
        userMapper.selectByExampleAndPage(page, example);
        return page;
    }

    @Override
    public int insertBatch(List<User> list) {
        return userMapper.insertBatch(list);
    }

    @Override
    public UserVO selectUserPermissionByUserName(String userName) {
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        criteria.andUsernameEqualTo(userName);
        example.setDistinct(true);
        return userMapper.selectUserPermissionByExample(example);
    }

    @Override
    public User login(String userName, String password) {
        if (StringUtils.isBlank(userName) || StringUtils.isBlank(password)) {
            throw new UnknownAccountException();
        }
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        criteria.andUsernameEqualTo(userName);
        criteria.andPasswordEqualTo(password);
        User user = null;
        List<User> list = userMapper.selectByExample(example);
        if(list.size()>0){
            user = list.get(0);
        }
        if (user == null) {
            throw new UnknownAccountException();
        }
        if(!"1".equals(user.getState())){
            throw new LockedAccountException();
        }
        return user;
    }

}
